from odoo import fields, models, api
from odoo.exceptions import UserError


class RESCounty(models.Model):
    _name = "res.county"
    _description = '县/区'

    @api.model
    def default_get(self, fields):
        res = super(RESCounty, self).default_get(fields)
        if self._context.get('city'):
            res.update({
                'city': self._context.get('city'),
            })
        return res

    name = fields.Char(string='名称', required=True)

    country_id = fields.Many2one(comodel_name='res.country', string='国家', required=True)
    state_id = fields.Many2one(comodel_name='res.country.state', string='省', domain=[('country_id', '=', country_id)], required=True)
    city_id = fields.Many2one(comodel_name='res.city', string='市', domain=[('state_id', '=', state_id)], required=True)

    # @api.constrains('name', 'country_id', 'state_id', 'city_id')
    # def _check_info(self):
    #     for s in self:
    #         if all([s.name, s.country_id, s.state_id, s.city_id]):
    #             rcds = self.env['res.county'].search([('name', '=', s.name),
    #                                                   ('country_id', '=', s.country_id.id),
    #                                                   ('state_id', '=', s.state_id.id),
    #                                                   ('city_id', '=', s.city_id.id)])
    #             if len(rcds) > 1:
    #                 raise UserError('同国、同省、同市中，县名不能相同')

    @api.onchange('country_id')
    def _onchange_state(self):
        if self.state_id and (self.state_id.id not in self.country_id.state_ids.ids):
            self.state_id = False

    @api.onchange('state_id')
    def _onchange_state_id(self):
        if self.city_id and self.city_id.state_id != self.city_id:
            self.city_id = False
